class WebSocketManager {
  constructor() {
    this.ws = null;
    this.messageHandlers = new Map();
    this.isConnecting = false;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 3;
  }

  connect() {
    if (this.ws && this.ws.readyState === 1) {
      return Promise.resolve();
    }

    if (this.isConnecting) {
      return new Promise((resolve) => {
        const checkConnection = setInterval(() => {
          if (this.ws && this.ws.readyState === 1) {
            clearInterval(checkConnection);
            resolve();
          }
        }, 100);
      });
    }

    this.isConnecting = true;

    return new Promise((resolve, reject) => {
      this.ws = wx.connectSocket({
        url: 'ws://localhost:3000',
        success: () => {
          console.log('WebSocket连接成功');
        }
      });

      this.ws.onOpen(() => {
        console.log('WebSocket连接已打开');
        this.isConnecting = false;
        this.reconnectAttempts = 0;
        resolve();
      });

      this.ws.onClose(() => {
        console.log('WebSocket连接已关闭');
        this.handleReconnect();
      });

      this.ws.onError((error) => {
        console.error('WebSocket错误:', error);
        reject(error);
      });

      this.ws.onMessage((res) => {
        const data = JSON.parse(res.data);
        this.handleMessage(data);
      });
    });
  }

  handleReconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      setTimeout(() => {
        this.connect();
      }, 1000 * this.reconnectAttempts);
    }
  }

  registerHandler(pageKey, handler) {
    this.messageHandlers.set(pageKey, handler);
  }

  unregisterHandler(pageKey) {
    this.messageHandlers.delete(pageKey);
  }

  handleMessage(data) {
    this.messageHandlers.forEach((handler) => {
      handler(data);
    });
  }

  send(data) {
    if (this.ws && this.ws.readyState === 1) {
      this.ws.send(JSON.stringify(data));
    } else {
      this.connect().then(() => {
        this.ws.send(JSON.stringify(data));
      });
    }
  }

  close() {
    if (this.ws) {
      this.ws.close();
    }
  }
}

const websocketManager = new WebSocketManager();
export default websocketManager; 